import { useFetch } from '@vueuse/core'
import { StorageCon } from '~/constant'
export const getRepoName = (userName, repoName) => {
  const url = `https://gitee.com/api/v5/repos/${userName}/${repoName}`
  const { isFetching, error, data } = useFetch(url)
  return {
    isFetching, error, data
  }
}
const stats = (list: {date: string, time: string, message: string}[]) => {
  const result = {}
  list.forEach(it => {
    if (result[it.date]) {
      result[it.date].push(it)
    } else {
      result[it.date] = [it]
    }
  })
  return result
}
const ErrorInfo = {
  Forbidden: '请求次数受限制',
  'Not Found': '仓库地址错误，或者是私有仓库'
}
export const getCommits = async (userName, repoName) => {
  const url = `https://gitee.com/api/v5/repos/${userName}/${repoName}/commits`
  const { isFetching, error, data } = await useFetch(url)
  // eslint-disable-next-line no-debugger
  debugger
  if (error.value) {
    // eslint-disable-next-line no-debugger
    // const msg = '没有找到'
    // if (error.value === 'Forbidden') {
    // }
    // eslint-disable-next-line prefer-promise-reject-errors
    return Promise.reject(ErrorInfo[error.value] || 'error')
  }
  const arr = JSON.parse(data.value as string) as Array<{commit: any, sha: string}>
  const result = arr.map(it => {
    const dateStr = it.commit.committer.date.substr(0, 10) // 2022-03-11
    const timeStr = it.commit.committer.date.substr(11, 8) // 15:54:30
    return {
      sha: it.sha,
      date: dateStr,
      time: timeStr,
      message: it.commit.message
    }
  })

  return {
    isFetching, error, data: stats(result)
  }
}

export const getStu = () : Student[] => {
  const stus = JSON.parse(localStorage.getItem(StorageCon.stu))
  return stus
}
// https://gitee.com/api/v5/repos/{owner}/{repo}
// https://gitee.com/zhoushugang/vue3-note
export const testUrl = (url) => {
  const { isFetching, error, data } = useFetch(url)
  return {
    isFetching, error, data
  }
}
